﻿// DlgModule.cpp: 实现文件
//

#include "pch.h"
#include "PE_Studio.h"
#include "afxdialogex.h"
#include "DlgModule.h"
#include <TlHelp32.h>
#include <strsafe.h>
// DlgModule 对话框

IMPLEMENT_DYNAMIC(DlgModule, CDialogEx)

DlgModule::DlgModule(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DLG_MODULE, pParent)
{
	m_pParent = (DlgProcess*)pParent;
}

DlgModule::~DlgModule()
{
}

void DlgModule::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_MODULE, m_ListModule);
}


BEGIN_MESSAGE_MAP(DlgModule, CDialogEx)
END_MESSAGE_MAP()


// DlgModule 消息处理程序
BOOL DlgModule::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// TODO:  在此添加额外的初始化
	m_ListModule.SetListCtrl(TRUE, TRUE, TRUE, FALSE, TRUE);
	m_ListModule.InsertColumn(0, TEXT(""), LVCFMT_CENTER, 50);
	m_ListModule.InsertColumn(1, TEXT("模块"), LVCFMT_CENTER, 340);
	m_ListModule.InsertColumn(2, TEXT("镜像基址"), LVCFMT_CENTER, 75);
	m_ListModule.InsertColumn(3, TEXT("镜像大小"), LVCFMT_CENTER, 75);
	m_ListModule.DeleteColumn(0);
    if (!InitModuleList())
    {
        return FALSE;
    }
	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}

BOOL DlgModule::InitModuleList()
{
	int nIndex = -1;
	int Index = 0;
	DWORD dwPID = 0;

	HANDLE hModuleSnap = NULL;
	MODULEENTRY32 me32;
	me32.dwSize = sizeof(MODULEENTRY32);
	TCHAR dwModBaseAddr[0x10] = { 0 };
	TCHAR dwModBaseSize[0x10] = { 0 };

	nIndex = m_pParent->m_ProcessListCtrl.GetSelectionMark();
	if (nIndex == -1)
	{
		return FALSE;
	}
	dwPID = _ttol(m_pParent->m_ProcessListCtrl.GetItemText(nIndex, 2));

	hModuleSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);
	if (INVALID_HANDLE_VALUE == hModuleSnap)
	{
		return FALSE;
	}
	
	if (!Module32First(hModuleSnap, &me32))
	{
		::CloseHandle(hModuleSnap);
		return FALSE;
	}
	do
	{
		StringCchPrintf(dwModBaseAddr, 0x10, TEXT("%p"), (DWORD)me32.modBaseAddr);
		StringCchPrintf(dwModBaseSize, 0x10, TEXT("%p"), me32.modBaseSize);
		m_ListModule.InsertItem(Index, me32.szExePath);
		m_ListModule.SetItemText(Index, 1, dwModBaseAddr);
		m_ListModule.SetItemText(Index, 2, dwModBaseSize);

	} while (Module32Next(hModuleSnap, &me32));
	::CloseHandle(hModuleSnap);
	return TRUE;
}

